package protocoltcp;


import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;

import java.util.UUID;


public class MyServerHander extends SimpleChannelInboundHandler<MessageProtocol> {
    private int count;

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, MessageProtocol msg) throws Exception {
        int len = msg.getLen();
        byte[] content = msg.getContent();
        System.out.println("服务器接受消息长度:" + len);
        System.out.println("服务器接受消息:" + new String(content, CharsetUtil.UTF_8));
        System.out.println("服务器接受消息次数:" + (++this.count));
        //回复消息
        String s = UUID.randomUUID().toString();
        int length = s.getBytes(CharsetUtil.UTF_8).length;
        byte[] bytes = s.getBytes(CharsetUtil.UTF_8);
        MessageProtocol messageProtocol = new MessageProtocol();
        messageProtocol.setLen(length);
        messageProtocol.setContent(bytes);
        channelHandlerContext.writeAndFlush(messageProtocol);
    }


    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
